package com.liuhm.exception;


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

/**
 * API统一响应结果
 *
 * @author lijian
 * @date 2019年11月7日15:29:13
 */

@ApiModel(description = "API统一响应结果")
public class R<T> implements Serializable {

    private static final long serialVersionUID = -2271896938471937687L;

    /**
     * 返回码
     */
    @ApiModelProperty(required = true, value = "状态码")
    private Integer code;
    /**
     * 返回信息
     */
    @ApiModelProperty(required = true, value = "返回信息")
    private String msg;
    /**
     * 请求时间
     */
    @ApiModelProperty(required = true, value = "时间")
    private Long time;
    /**
     * 异常信息
     */
    @ApiModelProperty(value = "异常信息")
    private String error;
    /**
     * 数据信息
     */
    @ApiModelProperty(required = true, value = "数据信息")
    private T data;

    public R(T data) {
        this(null, data);
    }

    public R(Integer code, T data) {
        if (null != code) {
            this.code = code;
        }
        this.time = System.currentTimeMillis();
        this.data = data;
    }

    public R() {
    }

    public R(Integer code, String msg, Long time, String error, T data) {
        this.code = code;
        this.msg = msg;
        this.time = time;
        this.error = error;
        this.data = data;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> R<T> fail() {
        return fail(null);
    }

    public static <T> R<T> fail(T data) {
        return new R<>(500, data);
    }

    public static <T> R<T> ok(T data) {
        return new R<>(200, data);
    }

    public static <T> R<T> ok() {
        return ok(null);
    }

    public static <T> R<T> data(T data) {
        return new R(data);
    }

    public R<T> msg(String msg) {
        this.setMsg(msg);
        return this;
    }

    public R<T> code(Integer code) {
        this.setCode(code);
        return this;
    }

    public R<T> error(String error) {
        this.setError(error);
        return this;
    }

    public R<T> exception(Exception e) {
        error(e.getMessage());
        return this;
    }


}